package com.mimiwang.article.service.impl;

import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mimiwang.article.dao.ArticleCategoryRelationDao;
import com.mimiwang.article.dao.ArticleInfoDao;
import com.mimiwang.article.dao.ArticlePhotoDao;
import com.mimiwang.article.entity.ArticleInfoEntity;
import com.mimiwang.article.service.ArticleCategoryRelationService;
import com.mimiwang.article.service.ArticleInfoService;
import com.mimiwang.article.service.ArticlePhotoService;
import com.mimiwang.article.util.ObjectToList;
import com.mimiwang.common.exception.BizCodeEnum;
import com.mimiwang.common.utils.JwtUtil;
import com.mimiwang.common.utils.PageUtils;
import com.mimiwang.common.utils.Query;
import com.mimiwang.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service("articleInfoService")
public class ArticleInfoServiceImpl extends ServiceImpl<ArticleInfoDao, ArticleInfoEntity> implements ArticleInfoService {

    @Autowired
    private ArticleInfoDao articleInfoDao;

    @Autowired
    private ArticlePhotoDao photoDao;

    @Autowired
    private ArticleCategoryRelationDao categoryRelationDao;


    @Autowired
    private ArticleCategoryRelationService categoryRelationService;

    @Autowired
    private ArticlePhotoService photoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ArticleInfoEntity> page = this.page(
                new Query<ArticleInfoEntity>().getPage(params),
                new QueryWrapper<ArticleInfoEntity>()
        );

        return new PageUtils(page);
    }

    /*点击写文章按钮，执行这个方法,判断是否登录*/
    @Override
    public String writeArticle(HttpServletRequest request) {
        /*获取用户*/
        Cookie[] cookies = request.getCookies();
        String token = cookies[0].getValue();
        Map<String, Claim> payloadFromToken = JwtUtil.getPayloadFromToken(token);
        String username = payloadFromToken.get("userName").asString();
        System.out.println("用户名是:"+username);
        String userId = payloadFromToken.get("userId").asString();
        Long aLong = Long.valueOf(userId);
        System.out.println("用户id是(long):"+aLong);
        /*判断是否登录*/
        if(userId!=null && username!=null){
            return token;
        }
        return null;
    }

    /*点击文章正式发布*/
    @Override
    @Transactional
    public R publish(Map<String, Object> map, HttpServletRequest request) {
        /*判断是否登录,获取用户id*/
        String token = writeArticle(request);
        if(token==null){
            return R.error(BizCodeEnum.NOT_LOGGED_NO);
        }
        Map<String, Claim> payloadFromToken = JwtUtil.getPayloadFromToken(token);
        String userId = payloadFromToken.get("userId").asString();
        Long userid = Long.valueOf(userId);
        /*图片是点击前端按钮，就先把图片上传到服务器里面，得到的url传过来，图片上传接口单独写*/
        /*获取文章基本信息，方便后面填充数据库，这里需要前端提前处理，保证信息这些不为空*/
        ArticleInfoEntity entity = null;
        ArrayList<Integer> categoryIds=null;
        List<String> arrayListPhoto=null;
        ObjectMapper objectMapper = new ObjectMapper();
        /*将map.get("key")获得的value转换为实体类*/
        try {
            String articleInfojsonInfo = objectMapper.writeValueAsString(map.get("articleInfo"));
            entity = objectMapper.readValue(articleInfojsonInfo, ArticleInfoEntity.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        /*将文章信息插入到数据库*/
        /*先看文章主页图片信息是否为空*/
        String icon = entity.getIcon();
        if(icon==null){
            return R.error(BizCodeEnum.ARTICLE_CLASSIFICATION);
        }
        categoryIds = (ArrayList<Integer>) map.get("categoryIds");
        arrayListPhoto = ObjectToList.castList(map.get("imgUrls"), String.class);
        entity.setUserId(userid);
        /*文章发布*/
        entity.setIsPublish(1);
        entity.setGmtPublish(new Date());
        articleInfoDao.insert(entity);
        /*获取自增id*/
        Long articleId = entity.getArticleId();
        /*将分类id存入数据库*/
        for (Integer categoryId : categoryIds) {
            categoryRelationService.saveCategoryId(articleId, (long)categoryId);
        }
        /*将图片存入数据库*/
        for (String s : arrayListPhoto) {
            photoService.savePhoto(articleId,s);
        }
        return R.ok(BizCodeEnum.ARTICLE_PUBLISHED_SUCCESSFULLY);

    }


    /*点击文章保存就执行这个方法*/
    @Override
    @Transactional
    public R saveArticle(Map<String, Object> map, HttpServletRequest request) {
        /*判断是否登录,获取用户id*/
        String token = writeArticle(request);
        if(token==null){
            return R.error(BizCodeEnum.NOT_LOGGED_NO);
        }
        Map<String, Claim> payloadFromToken = JwtUtil.getPayloadFromToken(token);
        String userId = payloadFromToken.get("userId").asString();
        Long userid = Long.valueOf(userId);
        /*图片是点击前端按钮，就先把图片上传到服务器里面，得到的url传过来，图片上传接口单独写*/
        /*获取文章基本信息，方便后面填充数据库，这里需要前端提前处理，保证信息这些不为空*/
        ArticleInfoEntity entity = null;
        ArrayList<Integer> categoryIds=null;
        List<String> arrayListPhoto=null;
        ObjectMapper objectMapper = new ObjectMapper();
        /*将map.get("key")获得的value转换为实体类*/
        try {
            String articleInfojsonInfo = objectMapper.writeValueAsString(map.get("articleInfo"));
            entity = objectMapper.readValue(articleInfojsonInfo, ArticleInfoEntity.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        /*将文章信息插入到数据库*/
        /*先看文章主页图片信息是否为空*/
        String icon = entity.getIcon();
        if(icon==null){
            return R.error(BizCodeEnum.ARTICLE_CLASSIFICATION);
        }
        categoryIds = (ArrayList<Integer>) map.get("categoryIds");
        arrayListPhoto = ObjectToList.castList(map.get("imgUrls"), String.class);
        entity.setUserId(userid);
        /*文章保存*/
        entity.setIsPublish(0);
        articleInfoDao.insert(entity);
        /*获取自增id*/
        Long articleId = entity.getArticleId();
        /*将分类id存入数据库*/
        for (Integer categoryId : categoryIds) {
            categoryRelationService.saveCategoryId(articleId,(long)categoryId);
        }
        /*将图片存入数据库*/
        for (String s : arrayListPhoto) {
            photoService.savePhoto(articleId,s);
        }
        return R.ok(BizCodeEnum.ARTICLE_SAVED_SUCCESSFULLY);
    }

    /*根据文章id进行删除，逻辑删除*/
    @Override
    public R deleteArticle(Integer articleId,HttpServletRequest request) {
        /*判断是否登录*/
        String token = writeArticle(request);
        if(token==null){
            return R.error(BizCodeEnum.NOT_LOGGED_NO);
        }
        /*删除逻辑*/
        ArticleInfoEntity entity = new ArticleInfoEntity();
        entity.setDeleted(1);
        QueryWrapper<ArticleInfoEntity> wrapper = new QueryWrapper<>();
        Long id = (long)articleId;
        wrapper.eq("article_id", id);
        int update = articleInfoDao.update(entity, wrapper);
        if(update==1){
            return R.ok(BizCodeEnum.ARTICLE_DELETED_SUCCESSFULLY);
        }
        return R.error(BizCodeEnum.ARTICLE_DELETION_FAILED);
    }

    /*点击编辑按钮，进行数据回显*/
    /**
     * categoryIds
     * articleInfo
     * imgUrls
     */
    @Override
    @Transactional
    public R updateArticle(Integer articleId, HttpServletRequest request) {
        /*判断用户是否登录*/
        String token = writeArticle(request);
        if(token==null){
            return R.error(BizCodeEnum.NOT_LOGGED_NO);
        }
        HashMap<String, Object> map = new HashMap<>();
        Long articleid=(long)articleId;
        ArticleInfoEntity infoEntity = articleInfoDao.selectById(articleid);
        map.put("articleInfo",infoEntity);
        /*根据文章id查询分类id*/
        List<Long> categoryIds = categoryRelationDao.selectByArticleId(articleid);
        map.put("categoryIds",categoryIds);
        /*根据文章id查询图片路径*/
        ArrayList<String> imgUrls = photoDao.selectByArticleId(articleid);
        map.put("imgUrls",imgUrls);
        System.out.println("mapmap:"+map);
        return R.ok(BizCodeEnum.PLEASE_EDIT).put("data", map);

    }


}